<template>
  <div class="admin-page-content">
    <el-form :model="service" :rules="serviceRules" ref="ruleForm" label-position="top" label-width="100px" class="servce-from demo-ruleForm">
      <el-row>
        <el-col :span="6">
          <el-form-item label="服务名称:" prop="base.name">
            <el-input v-model="service.base.name" placeholder="请输入服务名称" @blur="checkServiceName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="服务地址" prop="base.serviceUrl">
            {{base_url}}
            <el-input class="input-x" @blur="checkServceUrl" v-model="service.base.serviceUrl" placeholder="以/开头，不能包含其他特殊字符"></el-input>
          </el-form-item>
          
        </el-col>
        <el-col :span="7">
          <el-form-item label="数据库类型" prop="base.dbType">
             <el-select v-model="service.base.dbType" placeholder="请选择数据库类型" style="width:100%">
              <el-option label="Oracle" :value="0"></el-option>
              <el-option label="Hive" :value="1"></el-option>
              <el-option label="Kudu" :value="2"></el-option>
            </el-select>
           </el-form-item>
        </el-col>
      </el-row>
      <el-row>
           <el-col :span="6">
             <el-form-item label="使用状态" prop="base.status">
              <el-select v-model="service.base.status" placeholder="请选择服务返回方式" style="width:100%">
                <el-option label="待部署" :value="0"></el-option>
                <el-option label="启动" :value="1"></el-option>
                <el-option label="停用" :value="2"></el-option>
              </el-select>
            </el-form-item>
           </el-col>
          <el-col :span="service.base.resultType === 2 || service.base.resultType === 3 ? 11 : 18">
            <el-form-item label="服务返回方式" prop="base.resultType">
              <el-select @change="changeType" v-model="service.base.resultType"
                placeholder="请选择服务返回方式" style="width:100%" :disabled="service.id?true:false">
                <el-option label="JSON" :value="0"></el-option>
                <el-option label="XML" :value="1"></el-option>
                <el-option label="NAS" :value="2"></el-option>
                <el-option label="FTP" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" v-if="service.base.resultType === 2 || service.base.resultType === 3">
            <el-form-item label="文件服务器" prop="base.fileServerId">
              <el-select style="width:100%" v-model="service.base.fileServerId" :disabled="service.id?true:false">
                <el-option v-for="(item, key) in serviceData" :key="key"
                  :label="`${item.name} - ${item.host}`" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      <div class="add-params-box">
        <div class="btn-prams" @click="addParams">
          <i class="add-params"></i>
          <span>添加参数</span>
        </div>
      </div>
      <div class="params-row" v-if="service.params.length">
        <el-row v-for="(param,index) in service.params" :key="index">
          <el-col :span="4">
            <el-form-item label="参数显示名称" :prop="'params.'+index+'.paramShowname'"
              :rules="serviceRules.params.paramShowname">
              <el-input v-model="param.paramShowname" placeholder="参数显示名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="参数名称" :prop="'params.'+index+'.paramName'"
              :rules="serviceRules.params.paramName">
              <el-input v-model="param.paramName" placeholder="参数名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="字段类型">
              <el-select v-model="param.paramType" placeholder="字段类型" style="width:100%">
                <el-option value="string" label="string"></el-option>
                <el-option value="int" label="int"></el-option>
                <el-option value="double" label="double"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="是否必填" :prop="'params.'+index+'.required'"
              :rules="serviceRules.params.required">
              <el-select style="width:100%" v-model="param.required">
                <el-option :value="0" label="非必填"></el-option>
                <el-option :value="1" label="必填"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="参数可选值" :prop="'params.'+index+'.forSelect'"
              :rules="param.required === 1 ? [{required:true, message: '请输入', trigger: 'blur'}] : []">
              <el-input v-model="param.forSelect" placeholder="参数可选值"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="参数备注">
              <el-input v-model="param.paramDescription" placeholder="参数备注"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <div class="action-btn">
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i class="icon-table el-icon-delete" @click="deleteParams(param)"></i>
              </el-tooltip>
              <!-- <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <i class="icon-table el-icon-document-copy" @click="copyParamsSql(item)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="尾部添加" placement="top">
                <i class="icon-table el-icon-finished" @click="endInster(item)"></i>
              </el-tooltip> -->
            </div>
          </el-col>
        </el-row>
      </div>
      <el-row>
        <el-col :span="24" style="border:none;" class="dockerImage">
          <el-form-item label="Docker镜像地址" prop="dockerImage">
            <el-input placeholder="请输入docker镜像地址" v-model="service.dockerImage"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="page-btn-box">
        <div class="left-btx">
          <el-button type="primary" size="small" icon="el-icon-rank" @click="openProdDebug('ruleForm')">生产环境测试</el-button>
        </div>
        <div class="right-btx">
          <el-button type="info" size="small" icon="el-icon-arrow-left" @click="noSaveBack">不保存返回</el-button>
          <el-button type="primary" size="small" icon="el-icon-check"
            :disabled="!is_prd_debug" @click="saveFrom('ruleForm')">{{service.id?'修改':'新增'}}</el-button>
        </div>
      </div>
    </el-form>

    <el-drawer size="60%" :visible.sync="show_derawer"  :close-on-press-escape="false"
      :destroy-on-close="true"  :wrapperClosable="false" :before-close="closeDrawer">
      <div class="drawer-box">
        <div class="left-params">
          <el-form :model="prd_from" ref="prd_from" label-width="100px" label-position="top" class="demo-dynamic">
            <div class="title">条件选择</div>
            <div class="params-box rewiret-scoller reiewe-scolooer-color">
              <template v-for="(item,key) in prd_from.params">
                
                <el-form-item :key="key" :label="item.paramShowname"
                  :prop="'params.' + key + '.value'"
                  :rules="item.required === 1?[{ required: true, message: '请输入', trigger: !item.forSelect?'blur':'change' }]:[]">
                  <el-input  v-model="item.value" :placeholder="`请输入${item.paramShowname}`"
                    v-if="item.forSelect === '' || item.forSelect === null">
                  </el-input>
                  <!-- <el-select style="width:100%" v-model="item.value" :placeholder="`请选择${item.paramShowname}`"
                    v-if="item.forSelect !== '' && item.forSelect !== null">
                    <el-option v-for="(val,keys) in item.forSelect.split(',')" :value="val" :label="val" :key="keys"></el-option>
                  </el-select> -->
                  <el-autocomplete v-else v-model="item.value" :placeholder="`请选择或者输入${item.paramShowname}`"
                    :fetch-suggestions="querySearch" @focus="selectItem = item">
                  </el-autocomplete>
                </el-form-item>
              </template>
            </div>
            <div class="btn-box-left">
              <el-button type="primary" size="small" @click="devDebugInfos('prd_from')" :loading="loading_debug">
                {{loading_debug?'正在请求调试':'运行调试'}}
              </el-button>
              <el-button type="info" size="small" @click="saveResponse(debug_info)" :disabled="!is_request_debug">保存结果通知</el-button>
            </div>
          </el-form>
        </div>
        <div class="right-params">
          <div class="title">API服务实际URL</div>
          <div class="btn-right-left">
            <el-button type="primary" size="small" icon="el-icon-document-copy" @click="copyType(base_url+service.base.serviceUrl)">复制</el-button>
          </div>
          <el-input type="textarea" :autosize="{ minRows: 9, maxRows: 9}" readonly :value="`${base_url}${service.base.serviceUrl}`"></el-input>
          <div class="btn-right-left">
          <el-button type="primary" size="small" icon="el-icon-document-copy" :disabled="!is_request_debug" @click="copyType(debug_info)">复制</el-button>
        </div>
        <el-input type="textarea" :autosize="{ minRows: 9, maxRows: 9}" readonly :value="debug_info"></el-input>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getBaseUrl, getServiceFileAll, checkServiceUrls, checkServiceNames,
createService, updateService, getServiceInfo } from '@/api/admin/service';
import { createTempDebug, deleteTempDebug, callTempDebug } from '@/api/admin/debugInfo';
export default {
  data() {
    return {
      base_url: '',
      serviceData: [],
      serviceFile: [],
      service: {
        dockerImage: '',
        params: [],
        base: {
          dbType: '',
          fileServerId: '',
          name: '',
          resultType: '',
          serviceUrl: '',
          status: 0,
          type: 1
        }
      },
      serviceRules: {
        base: {
          name: [{required:true, message: '服务名称不可为空', trigger: 'blur'}],
          resultType: [{required:true, message: '服务返回方式不可为空', trigger: 'change'}],
          fileServerId: [{required:true, message: '文件服务器不可为空', trigger: 'change'}],
          status: [{required:true, message: '请选择使用状态', trigger: 'change'}],
          serviceUrl: [{required:true, message: '服务url不可为空', trigger: 'blur'}],
          dbType: [{required:true, message: '请选择数据库类型', trigger: 'change'}]
        },
        dockerImage:[{required:true, message: 'docker镜像地址不可为空', trigger: 'blur'}],
        params: {
          paramShowname: [{required:true, message: '请输入', trigger: 'blur'}],
          paramName: [{required:true, message: '请输入', trigger: 'blur'}],
          required: [{required:true, message: '请选择', trigger: 'change'}],
        }
      },
      is_prd_debug: false,
      show_derawer: false,
      prd_from: {
        params:[]
      },
      debug_info: '',
      is_request_debug: false,
      loading_debug: false,
      selectItem:{},
      time_end: false,
    }
  },
  created() {
    this.getInitData()
  },
  mounted() {
    if(this.$route.query.id) {
      this.getAdvancedInfo()
    }
  },
  methods: {
    querySearch(queryString, cb) {
      let temp = []
      for (const iterator of this.selectItem.forSelect.split(',')) {
        let value = {"value":iterator}
        temp.push(value)
      }
      cb(temp)
    },
    // 获取进阶服务信息
    async getAdvancedInfo() {
      const vm = this;
      let response = await getServiceInfo({id:vm.$route.query.id})
      if (response.code === '20000') {
        vm.service = {
          id: response.data.id,
          dockerImage: response.data.dockerImage,
          params: response.data.params,
          base: {
            dbType: response.data.base.dbType,
            fileServerId: response.data.base.fileServerId,
            name: response.data.base.name,
            resultType: response.data.base.resultType,
            serviceUrl: response.data.base.serviceUrl,
            status: response.data.base.status,
            type: response.data.base.type,
          }
        }
      }
    },
    async saveFromData() {
      const vm = this;
      let response;
      if (vm.service.id) {
        response = await updateService(vm.service)
      } else {
        response = await createService(vm.service)
      }
      if (response.code !== '20000') {
        vm.$alert(`保存进阶服务数据失败`,`温馨提示`,{
          confirmButtonText: '确定',
          callback: action => {
            console.log(action)
          }
        })
        return
      }
      vm.$message.success('保存成功')
      vm.$router.push({path: '/admin/service-manage/list'})
    },
    // 新增或者保存
    saveFrom(ruleFrom) {
      const vm = this;
      vm.$refs[ruleFrom].validate((valid)=>{
        if(valid){
          vm.saveFromData()
        }
      })
    },
    // 保存结果示例
    saveResponse(val) {
      this.service.base.returnDemo = val;
      this.$message.success('保存结果示例成功')
    },
    // 点击测试
    devDebugInfos(fromRule) {
      const vm = this;
      vm.$refs[fromRule].validate((valid)=>{
        if(valid) {
          let params = {
            tempId:vm.tempId
          }
          for (const val of vm.prd_from.params) {
            params[val.paramName] = val.value
          }
          vm.loading_debug = true
          callTempDebug(params).then((response)=>{
            vm.loading_debug = false
            if(response.code !== '20000') {
              vm.$alert(`调试失败,请检查Docker镜像地址或者参数`,`温馨提示`,{
                confirmButtonText: '确定',
                callback: action => {
                  console.log(action)
                }
              })
            } else {
              vm.is_request_debug = true;
              vm.debug_info = JSON.stringify(response.data)
            }
          })
        }
      })
    },
    // 拷贝
    copyType(val) {
      const vm = this;
      vm.$copyText(val).then(function(e){
        console.log(e)
        vm.$message.success('复制成功')
      },function (e){
        console.log(e)
        vm.$message.error('复制失败，您的浏览器不支持')
      })
    },
    // 删除生产环境生产
    closeDrawer(done) {
      const vm = this;
      const loading = this.$loading({
        lock: true,
        text: `正在清理生产临时测试环境,请耐心等待`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      deleteTempDebug({tempId:vm.tempId}).then((response)=>{
        if (response.code === '20000') {
          loading.close()
          vm.is_request_debug = false
          vm.debug_info = '';
          vm.show_derawer = false
          done()
        } else {
          vm.$alert(`清理临时测试环境失败,请稍后再试`,`温馨提示`,{
            confirmButtonText: '确定',
            callback: action => {
              console.log(action)
            }
          })
        }
      })
    },
    // 生产环境测试
    openProdDebug(ruleFrom) {
      const vm = this;
      vm.$refs[ruleFrom].validate((valid)=>{
        if(valid) {
          const loading = this.$loading({
            lock: true,
            text: `正在获取生产测试环境,请耐心等待,45秒`,
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          var time = 45;
          let interval = setInterval(function(){
            time --
            if(time>0){
              loading.setText(`正在获取生产测试环境,请耐心等待,${time}秒`)
            } if (time==0) {
              vm.nextDebguAction(loading,interval)
            }
          },1000)

          createTempDebug({dockerImage:vm.service.dockerImage}).then((response)=>{
            // loading.close()
            // clearInterval(interval)
            if(response.code === '20000'){
              vm.is_prd_debug = true
              vm.tempId = response.data.tempId
              let temp = []
              for (const item of vm.service.params) {
                let items = {
                  required: item.required,
                  paramName: item.paramName,
                  paramShowname: item.paramShowname,
                  forSelect: item.forSelect,
                  value:''
                }
                temp.push(items)
              }
              this.prd_from.params= temp
              // vm.show_derawer = true
            }
            // else {
            //   vm.$alert(`获取生产测试环境失败,请稍后再试`,`温馨提示`,{
            //     confirmButtonText: '确定',
            //     callback: action => {
            //       console.log(action)
            //     }
            //   })
            // }
          })
        }
      })
    },
    nextDebguAction(loading,interval) {
      const vm = this;
      clearInterval(interval)
      loading.close()
      if (vm.is_prd_debug) {
      vm.show_derawer = true
      } else {
        vm.$alert(`获取生产测试环境失败,请稍后再试`,`温馨提示`,{
          confirmButtonText: '确定',
          callback: action => {
            console.log(action)
          }
        })
      }
    },
    // 不保存返回
    async noSaveBack() {
      const vm = this;
      vm.$confirm(`退出保存您数据的数据将不会保存，请谨慎操作，是否继续`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(()=>{
        vm.$router.go(-1)
      })
      .catch(()=>{})
    },
    // 删除参数
    async deleteParams(item) {
      const vm = this;
      var index = vm.service.params.indexOf(item)
      if (index !== -1) {
        vm.service.params.splice(index,1)
      }
    },
    // 添加参数
    async addParams() {
      let temp = {
        paramShowname:'',
        paramName: '',
        paramType: '',
        required: 0,
        forSelect: '',
        paramDescription: '',
        sortNum:this.service.params.length
      }
      this.service.params.push(temp)
    },
    // 选择返回方式
    changeType(val) {
      const vm =this;
      vm.service.base.fileServerId = vm.service.id ? vm.service.base.fileServerId: ''
      if (val === 2 || val === 3) {
        vm.serviceData = vm.serviceFile.filter(function(item){
          if (val === 2 && item.type === 0) {
            return item
          }
          if (val === 3 && item.type === 1) {
            return item
          }
        })
      }
    },
    // 验证服务地址
    async checkServceUrl(event) {
      let value = event.target.value;
      const vm = this;
      let query = {
        serviceUrl: value
      }
      if (vm.service.id) {
        query.appId=vm.service.id
      }
      let response = await checkServiceUrls(query)
      if (response.code !== '20000') {
        vm.$message.error(`您输入的服务地址(${value}),${response.msg}`);
        vm.service.base.serviceUrl = '';
      }
    },
    // 验证服务名称
    async checkServiceName(event) {
      let value = event.target.value;
      const vm = this;
      let query = {
        serviceName : value
      }
      if (vm.service.id) {
        query.appId=vm.service.id
      }
      let response = await checkServiceNames(query)
      if (response.code !== '20000') {
        vm.$message.error(`您输入的服务名称(${value}),${response.msg}`);
        vm.service.base.serviceUrl = '';
      }
    },
    // 初始化页面数据
    async getInitData() {
      const vm = this;
      let beseUrlResponse = await getBaseUrl();
      if (beseUrlResponse.code === '20000') {
        vm.base_url = beseUrlResponse.data;
      }
      let service_file = await getServiceFileAll();
      if (service_file.code === '20000') {
        vm.serviceFile = service_file.data
      }
    }
  }
}
</script>
<style lang="scss" scoped>

.dest-text {
  font-size: 12px;
  color: red;
}

.page-btn-box {
  width: 100%;
  margin-top: 30px;
  overflow: hidden;
  .left-btx {
    float: left;
    overflow: hidden;
  }
  .right-btx {
    float: right;
    overflow: hidden;
  }
}
.desctdionx {
  width: 100%;
  overflow: hidden;
}
.input-x {
  width: 272px;
  border: 1px solid #dedede;
  font-size: 14px;
}
.input-x::placeholder {
  font-size: 14px;
}
.add-params-box {
  padding: 20px 0;
  overflow: hidden;
  .btn-prams {
    display: inline-block;
    cursor: pointer;
    color: #00a4ff;
    line-height: 20px;
    .add-params {
      display: inline-block;
      position: absolute;
      width: 20px;
      height: 20px;
      background-image: url(/imgs/add_icon.png) ;
      background-size: 100% 100%;
      
    }
    span {
      line-height: 20px;
      padding-left: 25px;
    }
  }
}
.params-row {
  padding-top:15px;
  width: 100%;
  overflow: hidden;
}
.action-btn {
  line-height: 71.5px;
  text-align: center;
}
.action-btn .icon-table:hover {
  color: #ffffff;
}
.row-top {
  margin-top: 15px;
}

.btn-right-left {
  padding: 10px;
  text-align: right;
  overflow: hidden;
}
.drawer-box {
  width: 100%;
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  .left-params {
    width: 40%;
    float: left;
    position: absolute;
    top: 0;
    bottom: 0;
    border-right: 1px solid #dedede;
    overflow: hidden;
    .params-box {
      margin:0 15px;
      height: 530px;
      overflow-y: scroll;
    }
    .params-box::-webkit-scrollbar {
      width: 2px;
      height: 1px;
    }

    .btn-box-left {
      position: absolute;
      right: 20px;
      bottom: 20px;
      text-align: right;
    }
  }
  .right-params {
    width: 57%;
    position: absolute;
    top: 0;
    right: 20px;
    bottom: 0;
    overflow: hidden;
  }
}
.title {
  font-size: 14px;
  color: #666666;
  padding: 10px;
}
</style>